﻿@using TD.Common.Kendo.Mvc5.Grid
@using TD.CTS.WebUI.Models

@model TD.CTS.Data.Filters.SchedulePlaningVisitDataFilter

@section head{
    <link href="@Url.Content("~/Content/td/td.kendo.grid.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/td/td.kendo.grid.js")"></script>
<style type="text/css">
    .timewindow-color {
        background-color: #dbe5f1;
    }
    .lwd-day {
        border-right-width: 2px !important;
    }
    .parentHeaderCol th {
         border-right-width: 2px !important;
    }
    .lwd-day-hdr{
         border-right-width: 2px !important;
    }

    .dayOfWeek { text-align:center;}
</style>

}

@{
    var filterRow = new TD.Common.Kendo.Mvc5.Grid.Filters.FilterRow(Html);
    var dt = ((ScheduleCalend)ViewBag.Calend).MonthYearDate;
    var dtColMin = ((ScheduleCalend)ViewBag.Calend).MinColDate;
    var dtColMax = ((ScheduleCalend)ViewBag.Calend).MaxColDate;
}

<table id="scheduleForm" class="td-formTable k-content" style="margin-top:0;">
    <tr>
        <td class="td-formTable-caption" style="width:100px;">Месяц</td>
        <td style="width:150px;">

            @(Html.Kendo().DatePicker()
                  .Name("monthpicker")
                  .Start(CalendarView.Year)
                  .Depth(CalendarView.Year)
                  .Format("MMMM yyyy")
                  //.Value("November 2011")
                  .Value(dt)
                  .HtmlAttributes(new { style = "width:150px", @onkeydown = "javascript:return false;" }))

        </td>
        <td class="td-formTable-caption" style="width:100px;">Пациент</td>
        <td style="width:250px;">@Html.EditorFor(model => model.PatientCode, "FormForeignKey")</td>
        
        
        

        <td style="width:250px;">
            @(Html.Kendo().Button().Name("ShowReportButton").SpriteCssClass("k-icon k-i-search").Content("Показать").HtmlAttributes(new { style = "width:230px;" }).Events(e => e.Click("ShowReport")))
        </td>
        <td></td>
    </tr>
</table>

        @(Html.Kendo().Grid<TD.CTS.Data.Entities.SchedulePlaningVisit>()
    .Init("SchedulePlaningVisitsGrid")
                //.Selectable()
    .Editable()
    .Reorderable(reorderable => reorderable.Columns(false))
    .Columns(columns =>
    {
        columns.Buttons(buttons => buttons.Edit()).Width(80).Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        columns.Bound(e => e.TrialCode).Width(80).Title("Код иссл.").Locked(true).HtmlAttributes(new { @class = "k-group-cell" }); 
        columns.Bound(e => e.TrialName).Width(100).Title("Исследование").Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        columns.Bound(e => e.PatientShortName).Width(150).Title("Пациент").Locked(true).HtmlAttributes(new { @class = "k-group-cell" }); 
        columns.Bound(e => e.TrialVisitName).Width(150).Title("Визит").Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        columns.Bound(e => e.MinDate).Width(90).Title("Дата нач.").Format("{0:dd.MM.yyyy}").Locked(true).HtmlAttributes(new { @class = "k-group-cell" }); 
        columns.Bound(e => e.MaxDate).Width(90).Title("Дата кон.").Format("{0:dd.MM.yyyy}").Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        //columns.Command(command => command.Custom("ViewVisitEmployees").Click("showVisitEmployees")).Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        columns.Bound(e => e.ScheduleDate).Width(90).Title("Дата план").Format("{0:dd.MM.yyyy}").Locked(true).HtmlAttributes(new { @class = "k-group-cell" });
        
        
        columns.Bound(e => e.VisitEmployeesString).Width(100).Locked(true)
            .ClientTemplate("<a class='k-button k-button-icontext k-grid-SchedulePlaningVisitsGrid' onclick='showVisitEmployees(" + "\"" + "#= VisitEmployeesString #" + "\"" + ")'><span></span>. . .</a>").Sortable(false)
            .Title("Сотрудники").Locked(true).HtmlAttributes(new { @class = "k-group-cell", @style = "white-space: nowrap", title = "#= VisitEmployeesString #" }); //HtmlAttributes(new { style = "white-space: normal" })

        var calend = (ScheduleCalend)ViewBag.Calend;
        //var calendDates = calend.dateList;
        foreach (var calendDate in calend.dateList)
        {
            columns.Template(e => { })
                .ClientTemplate("#= SelectedVisit(" + "\"" + calendDate.CalendDate.ToString("dd.MM.yyyy") + "\"" + ", data) #")
                .HeaderTemplate(string.Format(@"<span class='dayOfWeek' title='{1}'><input type='hidden' value='{1}'/>{0}</span>", calendDate.CalendDate.ToString("ddd"), calendDate.CalendDate.ToString("dd.MM.yyyy")))
                .HeaderHtmlAttributes(new { @class = (calendDate.LastDayInWeek) ? "lwd-day-hdr" : "day-hdr" })
                .Width(40)
                .HtmlAttributes(new {@style = "text-align:center;",@class=(calendDate.LastDayInWeek)?"lwd-day":""});
        }
        columns.Template(e => { }).ClientTemplate(" ").Width("100%").HtmlAttributes(new { @class = "k-group-cell" });

        //            columns.Template(e => { })<div style='text-align:center;'>{2}</div>
        //                .ClientTemplate(/*"<span style='color:red;'>!</span>"*/"#= SelectedVisit(" + visit.TrialVisitID + ", data) #")
        //                .HeaderTemplate(string.Format(@"<div style='text-align:center;'></span><input type='hidden' value='{2}'/></div>
        //<div style=""text-align:center;"">{0}</div><div style=""text-align:center;"">{1}</div>", visit.TrialVisitName, visit.ScheduleDate.HasValue ? visit.ScheduleDate.Value.Date.ToString("dd.MM.yyyy") : "", visit.TrialVisitID))
        //                .HtmlAttributes(new { style = "text-align:center;" })
        //                .Width(100);

        //            //buttonsRow.Append(@"<th style='text-align:center; style='text-align:right;><a class='k-button k-button-icontext k-grid-edit td-grid-button' href='\#' title='Изменить визит'><span class='k-icon k-edit td-grid-button-image'></span></a>");
        //            //buttonsRow.Append(@"<a class='k-button k-button-icontext k-grid-delete td-grid-button' href='\#' title='Удалить визит'><span class='k-icon k-delete td-grid-button-image'></span></a></th>");

    })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model =>
        {
            model.Id(e => e.ScheduleID);
            model.Id(e => e.TrialVisitID);
            model.Id(e => e.Id);
            model.Field(e => e.TrialCode).Editable(false);
            model.Field(e => e.TrialName).Editable(false);
            model.Field(e => e.PatientFullName).Editable(false);
            model.Field(e => e.TrialVisitName).Editable(false);
            model.Field(e => e.MinDate).Editable(false);
            model.Field(e => e.MaxDate).Editable(false);
            model.Field(e => e.ScheduleDate).Editable(false);
            model.Field(e => e.VisitEmployees).Editable(false);
            model.Field(e => e.VisitEmployeesString).Editable(false);


        })
        .Read(read => read.Action("GetVisits", "SchedulesPlanning", new {Model.PatientCode })/*.Data("kendo_grid_getfilters")*/)
        .Update(update => update.Action("UpdateScheduleVisit", "SchedulesPlanning"))
        .Events(events => events.Error("kendo_grid_error_handler"))
     )
    .Events(events => events.DataBound("onDataBound").Edit("OnSchedulesPlanningEdit").Cancel("OnSchedulesPlanningCancel").Save("OnSchedulesPlanningSave"))
)


@(Html.Kendo().Window().Name("VisitEmployeesWindow")
    .Title("Сотрудники")
    .Visible(false)
    .Modal(true)
    .Draggable(true)
    .Width(300)
      )
<script type="text/x-kendo-template" id="templateqwert">
    <div id="details-container">
        @*<h2>#= FirstName # #= LastName #</h2>
            <em>#= Title #</em>
            <dl>
                <dt>City: #= City #</dt>
                <dt>Address: #= Address #</dt>
            </dl>*@
        @*<p>Peoples: #=VisitEmployeesString #</p>*@
    </div>
</script>
<script>
    var minColDate = kendo.parseDate('@dtColMin.ToString("dd.MM.yyyy")', "dd.MM.yyyy");
    var maxColDate = kendo.parseDate('@dtColMax.ToString("dd.MM.yyyy")', "dd.MM.yyyy");

    var urlSaveVisit = "@Url.Action("UpdateScheduleVisit", "SchedulesPlanning")";
    var urlDelVisit = "@Url.Action("DeleteScheduleVisit", "SchedulesPlanning")";
    var grid;
    $(document).ready(function () {
        //$('#monthpicker').attr("readonly", "readonly");
        grid = $("#SchedulePlaningVisitsGrid");
        var headStr = "<tr id='trParentHeader' class='parentHeaderCol'>";
        grid.data("kendoGrid").thead.find('.dayOfWeek').each(function(index) {
            if ($(this).text() == 'Пн') {
                headStr += "<th colspan='7' class='k-header'>" + $(this).attr('title') + "</th>";
            }
            //} else {
            //    headStr += "<th  class='k-header'></th>";
            //}

        });
        headStr += "</tr>";

        //var myElem = document.getElementById('trParentHeader');
        //if (myElem == null) {
        grid.find("th.k-header").parent().first().before("<tr id='trParentHeader'><th colspan='9' class='k-header'>&nbsp</th></tr id='trParentHeader'>");
        grid.find("th.k-header").parent().last().before(headStr);
        //}

        kendo_grid_init(grid, true);

        //kendo_grid_init(grid, true, '@Html.Raw(filterRow.HtmlFilterRow())');
        grid.on("change", "input:checkbox", function() {
            if ($(this).is(":checked")) {
                grid.find('input:checkbox').not(this).prop('checked', false);

            }
        });
    });

    function OnSchedulesPlanningSave(arg) {
        arg.preventDefault();
        //1.Находим выбранную дату
        //1.1. Находим комбобокс с галочкой в строке
        var rowCb = arg.container.find('input:checkbox:checked').first();
        //Получаем ссылку на модель
        var model = arg.model;
        //1.2. Если есть выбранная галка
        if (rowCb.length > 0) {

            //находим дату из расписания и заданную
            var scheddate = model.ScheduleDate;
            var selectedDate = kendo.parseDate(rowCb.val(), "dd.MM.yyyy");

            //Если они отличаются
            if (!scheddate || !scheddate.sameDay(selectedDate)) {
                model.ScheduleDate = selectedDate;
                //model.dirty = true;
                SaveScheduleVisit(model, urlSaveVisit);
                //после вставки вычитать грид для обновления айдишки
                //if (model.Id == null) {
                    kendo_grid_reload(grid);
                //}
            } else {
                alert('Дата не изменилась');
            }
        } else {
            //Если галка не выбрана
            if (model.Id != null) {

                //var minjsColDate = kendo.parseDate(minColDate, "dd.MM.yyyy");
                //var maxjsColDate = kendo.parseDate(maxColDate, "dd.MM.yyyy");
                //если дата планирования входит в отображаемое окно- то удаляем
                if (model.ScheduleDate >= minColDate && model.ScheduleDate <= maxColDate) {
                    //И есть код визита
                    SaveScheduleVisit(model, urlDelVisit);
                    kendo_grid_reload(grid);
                }


            } else {

                alert("Выберите дату");
            }

        }
    }


    function OnSchedulesPlanningCancel(arg) {
        arg.preventDefault();
        kendo_grid_reload(grid);
        // $("#SchedulePlaningVisitsGrid").data("kendoGrid").cancelRow();
    }


    function SaveScheduleVisit(data, url) {
       //Модифицируем дату чтобы правильно конвертилась в джейсон
       data.ScheduleDate.setHours(data.ScheduleDate.getHours() - data.ScheduleDate.getTimezoneOffset() / 60);

        var sendData =
        {
            "Id": data.Id,
            "ScheduleID": data.ScheduleID,
            "TrialVisitID": data.TrialVisitID,
            "TrialCenterID": data.TrialCenterID,
            "TrialCode": data.TrialCode,
            "TrialVersionNo": data.TrialVersionNo,
            "ScheduleDate": data.ScheduleDate.toJSON(),
            "ActualDate": data.ActualDate
        };


        $.ajax({
            type: "POST",
            url: url,
            data: sendData,
            async: false,
            success: function(/*newVisit*/) {
                //alert(newVisit);
                //if (checked) {
                //    rowData.Visits.push(newVisit);
                //} else {
                //    rowData.Visits.splice(index, 1);
                //}
                //grid.dataSource.pushUpdate(rowData);
                //selectedCell.html(SelectedVisit(visitId, rowData));
            },
            error: function(error) {
                AjaxError(error);
            }
        });
    }

    function SelectedVisit(calendDateStr, data) {
        var calendDate = kendo.parseDate(calendDateStr, "dd.MM.yyyy");
        //var retStr = '';
        var div = $('<div>');
        //Созлаем инпут
        var input = $('<input type=\"checkbox\" class=\"k-checkbox\" style=\"margin:0;display:none;\" />').val(calendDateStr);

        //Проверяем входит ли заданная дата из колонки в окно визита
        //if (calendDate >= data.MinDate && calendDate <= data.MaxDate) {
        //    div.addClass('timewindow');
            div.append(input);

        //}
        //если дата календаря равна дате визита
        if (data.ScheduleDate != null && calendDate.sameDay(data.ScheduleDate)) {
            input.attr('checked', 'checked');
            div.append('<span class=\"k-icon k-i-tick td-activeTick\"></span>');
        }


        var retStr = div[0].outerHTML;

        return retStr;

    }

    function onDataBound(/*arg*/) {
        $('.timewindow').parents('td').addClass("timewindow-color");
        var grid = $("#SchedulePlaningVisitsGrid").data("kendoGrid");
        var data = grid.dataSource.data();

        $.each(data, function(i, row) {
            var status = row.RankState;

            if (status == 1) {
                $('tr[data-uid="' + row.uid + '"] ').css("color", "orange"); //green
            }
            if (status == 2) {
                $('tr[data-uid="' + row.uid + '"] ').css("color", "red"); //yellow
            }
        });
    }


    function OnSchedulesPlanningEdit(e) {
        //1.Переводим в режим редактирования строку
        //удаляем иконки
        e.container.find('span.k-i-tick').remove();
        //отображаем инпуты
        e.container.find('input:checkbox').css("display", "inline-block");
        kendo_grid_onrowedit(e);
    }

    var validator = $("#scheduleForm").kendoValidator().data("kendoValidator");

    function ShowReport() {
        //if (validator.validate()) {
        var monthControl = $("#monthpicker").data("kendoDatePicker");
        var monthControlVal = monthControl.value();
        if (monthControlVal != null) {
            var data =
            {
                year: monthControlVal.getFullYear(),
                month: monthControlVal.getMonth() + 1,
                PatientCode: $('#PatientCode').val()
            };

            $().redirect("@Url.Action("Index", "SchedulesPlanning")", data);
        }
        //  }
    }










    //function ClearSelection() {
    //    var grid = $("#SchedulePlaningVisitsGrid").data("kendoGrid");
    //    selectedCell = null;
    //    grid.clearSelection();
    //}
    @*function Update(){
        var result = true;
        if(selectedCell != null){
            var input = selectedCell.find("input");
            var checked = input.is(':checked');
            var visitId = parseInt(input.val());
            var row = selectedCell.closest("tr");
            var grid = $("#SchedulePlaningVisitsGrid").data("kendoGrid");
            var rowData = grid.dataItem(row);
            var inArray = $.inArray(visitId, rowData.VisitIds) !== -1;
            if((checked && inArray) || (!checked && !inArray)){
                selectedCell.html(SelectedVisit(visitId, rowData));
                return result;
            }
            var values = $(row).find('input:checkbox:checked').map(function () {
                return parseInt(this.value);
            }).get();

            var newRow = {
                "Id": rowData.Id,
                "ProcedureCode": rowData.ProcedureCode,
                "TrialCode": rowData.TrialCode,
                "VisitIds": values
            };

            $.ajax({
                type: "POST",
                url: "@Url.Action("UpdateTrialProcedure", "Trials")",
                data: newRow,
            async: false,
            success: function (data) {
                //rowData.VisitIds = values;
                grid.dataSource.pushUpdate(newRow);
                selectedCell.html(SelectedVisit(visitId, rowData));
            },
            error: function (error) {
                result = false;
                grid.select(selectedCell);
                AjaxError(error);
            }
        });
    }

    return result;
        }*@

    //------------------------Сравниваем даты по дню---------------------------------------
    Date.prototype.sameDay = function (d) {
        return this.getFullYear() === d.getFullYear()
            && this.getDate() === d.getDate()
            && this.getMonth() === d.getMonth();
    };
    Date.prototype.withoutTime = function () {
        var d = new Date(this);
        d.setHours(0, 0, 0, 0, 0);
        return d;
    };


    var detailsTemplate = kendo.template($("#templateqwert").html());
    //-------------------------- Нажатие кнопки показа сотрудников ------------------------
    function showVisitEmployees(e) {
        //e.preventDefault();
        //находим строку
        //var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        //находим окно
        var wnd = $("#VisitEmployeesWindow").data("kendoWindow");
        //вставляем темплейт
        //wnd.content(detailsTemplate(dataItem));
        wnd.content(e);
        //открываем окно
        wnd.center().open();
    }

</script>
